package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.YiRongGuangGaoParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class YiRongGuangGaoReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret().substring(0, 16);
        String channelCode = sourceBaseInfo.getChannelCode();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String channelCode1 = jsonObjectParamContent.getString("source");
        if (!channelCode.equals(channelCode1)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的渠道编号不符"));
            return sourceApiResult;
        }

        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("name")) || StrUtil.isEmpty(jsonObject.getString("mobile_md5")) || StrUtil.isEmpty(jsonObject.getString("city")) ||
                jsonObject.getInteger("car") == null || jsonObject.getInteger("gongjijin") == null || jsonObject.getInteger("shebao") == null ||
                jsonObject.getInteger("house") == null || jsonObject.getInteger("baodan_is") == null || jsonObject.getInteger("credit_card") == null ||
                jsonObject.getInteger("job") == null || jsonObject.getInteger("age") == null || jsonObject.getInteger("sex") == null ||
                jsonObject.getInteger("money") == null || jsonObject.getInteger("zhima_score") == null || jsonObject.getInteger("education") == null || StrUtil.isEmpty(jsonObject.getString("ip"))){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 通过城市编码,获取城市信息
        String city = jsonObject.getString("city");

        AddressInfo addressInfo = addressInfoService.getAddresInfoByCity(city+"市");
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret().substring(0, 16);

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("data");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(content);

        YiRongGuangGaoParam yiRongGuangGaoParam = JSON.parseObject(paramContentData, YiRongGuangGaoParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(yiRongGuangGaoParam.getMobile());
        userDataParam.setRealName(yiRongGuangGaoParam.getName());

        String productId = yiRongGuangGaoParam.getRequestId();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), productId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", "200");
        returnObject.put("msg", "匹配成功！");
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        dataObject.put("status", "1");
        dataObject.put("requestId", pushResultInfo.getOutOrderNo());

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            // 下游是 非 apis 类型
            dataObject.put("institutionName", thirdBaseInfo.getCompanyName());
            dataObject.put("company", thirdBaseInfo.getCompanyName());
            dataObject.put("companyAddress", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }

            dataObject.put("productName", thirdBaseInfo.getProductName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());
            dataObject.put("price", pushResultInfo.getPriceAmount());

            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name",protocolInfo.getProtocolName());
                jsonObject.put("url", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else {
            dataObject.put("institutionName", merchantBaseInfo.getCompanyName());
            dataObject.put("company", merchantBaseInfo.getCompanyName());
            dataObject.put("companyAddress", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }

            dataObject.put("productName", merchantBaseInfo.getInfoName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());
            dataObject.put("price", String.valueOf(sourceBaseInfo.getPriceAmount()));
            //协议地址

            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("name","授权协议");
            jsonObject.put("url", protocolUrl);
            jsonArray.add(jsonObject);
        }

        dataObject.put("agreementList", jsonArray);
        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status","1");
                jsonObject.put("orderSn",UUID.randomUUID().toString());
                jsonObject.put("requestId",UUID.randomUUID().toString());
                returnObject.put("data",jsonObject);
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status","0");
        jsonObject.put("requestId",UUID.randomUUID().toString());
        returnObject.put("data",jsonObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", "200");
        returnObject.put("msg", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", "200");
        returnObject.put("msg", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        YiRongGuangGaoParam yiRongGuangGaoParam = JSON.parseObject(paramContent, YiRongGuangGaoParam.class);

        UserDataParam userDataParam = new UserDataParam();

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        userDataParam.setMobileMd5(yiRongGuangGaoParam.getMobile_md5());
        userDataParam.setMobile(yiRongGuangGaoParam.getMobile());
        userDataParam.setRealName(yiRongGuangGaoParam.getName());

        Integer sex = yiRongGuangGaoParam.getSex();
        if (sex == 0){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }


        userDataParam.setAge(Integer.valueOf(yiRongGuangGaoParam.getAge()));
        userDataParam.setCityCode(yiRongGuangGaoParam.getCity_code());


        Integer creditCardLimit = yiRongGuangGaoParam.getCredit_card();
        if (creditCardLimit == 0){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
        }

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());

        Integer education = yiRongGuangGaoParam.getEducation();
        if (education == 0){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl002.getValue());
        }else if (education == 1){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl003.getValue());
        }else if (education == 2){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl004.getValue());
        }else if (education == 3){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl005.getValue());
        }else {
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        }

        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());

        Integer baitiao = yiRongGuangGaoParam.getBaitiao();
        if (baitiao == null){
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        }else {
            if (baitiao == 0){
                userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
            }else{
                userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt002.getValue());
            }
        }


        Integer huabei = yiRongGuangGaoParam.getHuabei();
        if (huabei == null){
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        }else {
            if (huabei == 0){
                userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
            }else {
                userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb002.getValue());
            }
        }


        String ip = yiRongGuangGaoParam.getIp();
        if (StringUtils.isNotEmpty(ip)){
            userDataParam.setUserIp(ip);
        }else {
            userDataParam.setUserIp("127.0.0.1");
        }


        Integer loanAmount = yiRongGuangGaoParam.getMoney();
        if (Integer.valueOf(loanAmount) <= 30000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (Integer.valueOf(loanAmount) > 30000 && Integer.valueOf(loanAmount) <= 50000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (Integer.valueOf(loanAmount) > 50000 && Integer.valueOf(loanAmount) <= 100000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (Integer.valueOf(loanAmount) >100000 && Integer.valueOf(loanAmount) <= 200000) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }


        Integer houseProperty = yiRongGuangGaoParam.getHouse();
        if (houseProperty == 0){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }


        Integer baodanIs = yiRongGuangGaoParam.getBaodan_is();
        if (baodanIs == 0){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }


        Integer overdue = yiRongGuangGaoParam.getOverdue();
        if (overdue == null){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else {
            if (overdue == 0){
                userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
            }else if (overdue == 1){
                userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq003.getValue());
            }else {
                userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
            }
        }


        Integer gongjijin = yiRongGuangGaoParam.getGongjijin();
        if (gongjijin == 0){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else if (gongjijin == 1){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        Integer zhimaScore = yiRongGuangGaoParam.getZhima_score();
        if (zhimaScore == 0){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }else if (zhimaScore == 1){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if (zhimaScore == 2){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if (zhimaScore == 3){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }

        Integer shebao = yiRongGuangGaoParam.getShebao();
        if (shebao == 0){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else if (shebao == 1){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        Integer car = yiRongGuangGaoParam.getCar();
        if (car == 0){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }



        Integer job = yiRongGuangGaoParam.getJob();
        if (job == 1){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (job == 2){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if (job == 0){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }

        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());


        return userDataParam;
    }


}
